package com.gack.business.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.gack.business.vo.ContactsDetailVO;

import io.jsonwebtoken.lang.Collections;

/**
 * 
 * @author ws
 * 2018-6-22
 */
@Repository
public class EnterpriseDao {

	@Autowired
	private EntityManager em;
	
	/**
	 * 根据公司id集合和用户id查询公司卡片对象集合
	 * @param userId 用户id
	 * @param enterpriseIdList 公司id集合
	 * @return
	 */
	public List<ContactsDetailVO.CompanyCard> findCompanyCardByEnterpriseIdAndUserId(String userId, List<String> enterpriseIdList){
	
		if(Collections.isEmpty(enterpriseIdList)){
			return new ArrayList<ContactsDetailVO.CompanyCard>();
		}
		
		String jpql = "select new com.gack.business.vo.ContactsDetailVO$CompanyCard("
					+ " uedp.enterpriseId as id,"
					+ " (select name from Enterprise where id=uedp.enterpriseId) as name,"
					+ " uedp.enterpriseRemarks,"
					+ " uedp.departmentId as department_name,"
					+ " (select name from Position where id=uedp.positionId) as position_name"
					+ ")"
					+ " from UserEnterpriseDepartmentPosition uedp"
					+ " where uedp.userId=:userId and enterpriseId in ";
		
		StringBuilder sb = new StringBuilder();
		sb.append("(");
		for(String t : enterpriseIdList){
			 sb.append(" '" + t + "',");
		}
		sb = new StringBuilder(sb.substring(0, sb.length()-1));//去掉最后的","
		sb.append(")");//最后一个括号是子查询的右括号
		
		jpql += sb.toString();
		
		Query query = em.createQuery(jpql);
		query.setParameter("userId", userId);
		
		return query.getResultList();
	}
	
}
